package com.icinfo.cloud.provider.common.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * 获得http请求头工具
 * @author
 */
public class HeaderUtil {
	public static final Log log = LogFactory.getLog(HeaderUtil.class);

	public static Map<String, String> headerInfo() {
		HttpServletRequest request = getHttpServletRequest();
		Map<String, String> headers = getHeaders(request);
		return  headers;
	}

	private static HttpServletRequest getHttpServletRequest() {

		try {
			// 这种方式获取的HttpServletRequest是线程安全的
			return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
		} catch (Exception e) {

			return null;
		}
	}

	private static Map<String, String> getHeaders(HttpServletRequest request) {

		Map<String, String> map = new LinkedHashMap<>();
		if (request != null && request.getHeaderNames() != null) {
			Enumeration<String> enums = request.getHeaderNames();
			while (enums.hasMoreElements()) {
				String key = enums.nextElement();
				String value = request.getHeader(key);
				map.put(key, value);
			}
		}

		return map;
	}
	
}
